<?php
require_once ROOT_PATH.'boot/req_inc.php';

//web页面模板处理
if(!defined('WEB_PAGE_TPL')) define('WEB_PAGE_TPL','web_page.tpl.php'); //web页面模板
if(!defined('WEB_PAGE_ERR_TPL')) define('WEB_PAGE_ERR_TPL','web_page_error.tpl.php'); //错误页面模板
if(! defined('RUN_WIDGET') || ! RUN_WIDGET){
	function render_widget($widget_id){}
}
if(! defined('RUN_CONTROL') || ! RUN_CONTROL){
	function render_control($clazz,$id,array $options=array()){}
}
function get_web_page($tpl_file, $page='') {
	$WEB_PAGE_TPL = WEB_PAGE_TPL;
	if($page) $WEB_PAGE_TPL = str_replace('web_page', 'web_page_'.$page, $WEB_PAGE_TPL);
	$dirpath = dirname ( $tpl_file );
	if (! $dirpath)	return $WEB_PAGE_TPL;
	if (DS != '/')	$dirpath = str_replace ( '/', DS, $dirpath );
	if ($dirpath == '/' || $dirpath == '/')	return $dirpath . $WEB_PAGE_TPL;
	if (file_exists ( $dirpath . DS . $WEB_PAGE_TPL )) return $dirpath . DS . $WEB_PAGE_TPL;

	$ctx = $GLOBALS ['context'];
	$views_path = ROOT_PATH . $ctx->app_name . DS . 'views';
	if ($ctx->theme) $views_path .= DS . $ctx->theme;
	if( defined('RUN_MLANG_VIEW') && RUN_MLANG_VIEW) $views_path.=$ctx->app_lang .DS ;

	while ( $dirpath && $dirpath != DS && $dirpath != $views_path ) {
		$pos = strrpos ( $dirpath, DS );
		$dirpath = substr ( $dirpath, 0, $pos );
		if (file_exists ( $dirpath . DS . $WEB_PAGE_TPL )) return $dirpath . DS . $WEB_PAGE_TPL;
	}
}
if(! function_exists('get_tpl_path')){
	function get_tpl_path($tplname) {
		global $context;
		$views_path=ROOT_PATH . $context->app_name . DS.'views'. DS ;
		if($context->theme) $views_path.=$context->theme .DS ;
		if( defined('RUN_MLANG_VIEW') && RUN_MLANG_VIEW) $views_path.=$context->app_lang .DS ;
		if('/'!==DS) $tplname=str_replace('/',DS,$tplname);
		return $views_path.$tplname.'.tpl.php';
	}
}
/**
 * 放置分页条
 * @param array  $page_info 分页信息   TableMapper->get_page_info函数返回值,@see TableMapper
 * @param string $page_link  页码链接模板
 * @param string $page_tpl   分页条模板文件，在views模板目录的pagination子目录下，默认值page，即page.tpl.php文件。
 */
function put_pagination(array $page_info, $page_link, $page_tpl = 'page') {
	$_fa_file_X3f7t_o0z8 = get_tpl_path ( 'pagination' . DS . $page_tpl );
	if (! file_exists ( $_fa_file_X3f7t_o0z8 )) {
		global $context;
		$context->log_error ( "pagination [{$_fa_file_X3f7t_o0z8}] NOT FOUND" );
	} else {
		unset ( $page_tpl );
		include $_fa_file_X3f7t_o0z8;
	}
}

//end web页面模板处理

class HtmlRenderer implements IReponseRenderer {
	private function render_error(array & $app,$view_path,$none_page){
		if($app['err_no']==0) return;
		if(! file_exists( $view_path. WEB_PAGE_ERR_TPL)){
			$GLOBALS['context']->log_error ( 'ERROR PAGE TEMPLATE '.$view_path. WEB_PAGE_ERR_TPL .' NOT FOUND!'  );
			echo '<html><head>';
			if(isset($app['title'])) 	echo '<title>'.$app['title'].'</title></head><body>';
 			echo '<h1>ERROR PAGE TEMPLATE NOT FOUND!</h1></body></html>';
 			exit;
		}
		if($none_page) include $view_path. WEB_PAGE_ERR_TPL;
		else{	//add head and tail for app_page=null,WEB_PAGE_ERR_TPL is not full page
			/*
			echo "<html><head>\n<meta http-equiv='content-Type' content='text/html; charset=".
				$GLOBALS['context']->get_app_conf('charset') ."'/>\n";
			if(isset($app['title'])) 	echo '<title>'.$app['title']."</title></head><body>";
 			include $view_path. WEB_PAGE_ERR_TPL;
			echo "\n</body></html>";
			*/
			include $view_path. WEB_PAGE_ERR_TPL;
		}
		exit;
	}
	function render(array & $request,array & $response,  array & $app) {
		if ($app ['fmt'] !== 'html') return;

		$context=$GLOBALS['context'];
		$webpage_charset=$context->get_app_conf('charset');
		header('Content-Type: text/html;charset='.$webpage_charset);

		if(isset($app ['ttl']) && $app ['ttl']>0)	header("Cache-Control:max-age={$app ['ttl']}");
		$_none_page=isset($app['page'])&& strcasecmp($app['page'],'NULL')==0;
		$_views_path=ROOT_PATH . $context->app_name . DS.'views'. DS ;
		if(isset($request['profile'])){
			//$context->theme = $request['profile'];
			$current_template = $context->get_session('current_template', true);
			$context->theme =  $current_template;
		}else{
			if($context->theme && $app['name'] != 'webadmin'){
				$template = @file_get_contents($_views_path . 'template.log');
                $template = trim($template);
				if(!empty($template)){
					$context->theme = $template;
				}else{
					$row = $context->db->create_mapper('system_config')
						->select('value')
						->where(array('code'=>'shop_template_'.$app['name']))
						->find_by();
					if(empty($row)){
						$row = $context->db->create_mapper('system_config')
							->select('value')
							->where(array('code'=>'shop_template'))
							->find_by();
					}
					$context->theme = !empty($row) ? $row['value'] : 'default';
					@file_put_contents($_views_path . 'template.log', $context->theme);
				}
			}
		}
		$_views_path .= $context->theme . DS ;

		if( defined('RUN_MLANG_VIEW') && RUN_MLANG_VIEW) $_views_path .= $context->app_lang .DS ;
		if($app['err_no']!==0) $this->render_error($app,$_views_path,$_none_page);
//        $app['plugin_tpl_path'] = 1;
        if(isset($app['plugin_tpl_path']) && $app['plugin_tpl_path']) {
            $_views_path=ROOT_PATH . $context->app_name . DS.'plugins'. DS.$app['plugin_tpl_path'] ;
        }
//        print_r($app);
//        echo $_views_path;

		if(isset($app['tpl']) && $app['tpl']){
			$main_child_tpl=$app['tpl'];
			if($main_child_tpl[1]!==':' && $main_child_tpl[0]!=='/') 	//not absolute page path
				$main_child_tpl= $_views_path."{$main_child_tpl}.tpl.php";
		}
		else{
			$main_child_tpl= $_views_path."{$context->app_path}";
			
			if(defined('RUN_TPL_DIR') && RUN_TPL_DIR) $main_child_tpl.= $app['grp'] . DS;
			$main_child_tpl .= "{$app['grp']}_{$app['act']}.tpl.php";
		}

		if(! file_exists($main_child_tpl)){
			$app['err_no']=20001;
			$app['err_msg']=lang('req_err_not_found_tpl').'['. $main_child_tpl.']';
			$this->render_error($app,$_views_path,$_none_page);
		}

		if ($_none_page) {
			$_FASTAPP_web_page_file_3D8jKw5L2q=$main_child_tpl;
			unset($main_child_tpl);
			include $_FASTAPP_web_page_file_3D8jKw5L2q;
			return true;
		} else {
			ob_start();

			if (! isset ( $app ['page'] )) $_web_page_file = get_web_page ( $main_child_tpl );
			else{
				$_web_page_file = get_web_page ( $main_child_tpl, $app ['page'] );
				if(! file_exists($_web_page_file)){
					$_web_page_file = $app ['page'];
					/*  由于安全原因，取消app_page使用绝对路径特性，即app_page必须在对应的views目录theme子目录下
					//if($_web_page_file[1]!==':' && $_web_page_file[0]!=='/') 	//not absolute page path
					*/
					$_web_page_file = $_views_path . $_web_page_file . '.tpl.php';
				}
			}
			$_FASTAPP_web_page_file_3D8jKw5L2q=$_web_page_file;
			unset ( $_views_path );
			unset ( $_none_page );
			unset ( $_web_page_file );

			if (file_exists ( $_FASTAPP_web_page_file_3D8jKw5L2q )) {
				include $_FASTAPP_web_page_file_3D8jKw5L2q;			//the file MUST NOT contain var $main_child_tpl
			} else {
				$_FASTAPP_web_page_file_3D8jKw5L2q=$main_child_tpl;
				unset($main_child_tpl);
				echo "<html><head>\n<meta http-equiv='content-Type' content='text/html; charset=".
					$GLOBALS['context']->get_app_conf('charset')."' />\n";
				if (isset ( $app ['title'] ))	echo '<title>' . $app ['title'] . "</title></head><body>\n";
				include $_FASTAPP_web_page_file_3D8jKw5L2q;
				echo "\n</body></html>";
			}

			$html = ob_get_contents();
			ob_end_clean();
			echo $html;

			$static_list = $context->get_app_conf('static_list');
			if (!empty($static_list)) {
				$cache_lifetime = $context->shop_conf->get('cache_lifetime',300);

				$main_child_act = str_replace('/', '_', trim($context->action, '/'));
				if (isset($static_list[$main_child_act]) && $static_list[$main_child_act]) {
					$file_name = urldecode(trim($_SERVER['REQUEST_URI'], '/'));
					/*
					//WINDOWS服务器需编码转换
					$charset = $GLOBALS['context']->get_app_conf('charset');
					$charsets = $GLOBALS['context']->get_app_conf('charsets');
					if ($charsets == '') {
						$charsets = 'GBK, GB2312';
					}
					$in_charset = mb_detect_encoding($file_name, $charsets);
					$file_name = mb_convert_encoding($file_name, $in_charset, $charset);
					*/
					if ($file_name == '') {
						$file_name = 'index.html';
					}
					switch($static_list[$main_child_act]){
						case 1:
							$context->html_cache->set_path(STATIC_PAGE_PATH);
							break;
						case 2:
							$context->html_cache->set_path('web');
							break;
						default:
							break;
					}
					$context->html_cache->set($file_name, $html, $cache_lifetime, false);
				}
			}

			return true;
		}
	}
}

